<!--新建固件-->
<template>
  <el-dialog
    :title="addOrEditType === 'add' ? '新建固件版本' : '编辑固件版本'"
    :visible.sync="firmwareVersionVisible"
    width="628px"
    :before-close="handleClose"
    :close-on-click-modal="false">
    <el-form ref="form" :rules="rules" :model="form" label-width="160px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="固件名称" prop="name">
            <template #label>
              <span>固件名称</span>&nbsp;
              <el-tooltip content="仅用于管理固件，不对外显示" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input
              v-if="addOrEditType === 'add' && pageType === 'firmwareDetails'"
              v-model="form.name"
              maxlength="32"
              show-word-limit
              placeholder="请输入固件名称"></el-input>
            <span v-else>{{ form.name }}</span>
          </el-form-item>
          <el-form-item label="固件版本" prop="version">
            <template #label>
              <span>固件版本</span>&nbsp;
              <el-tooltip placement="top">
                <template #content>
                  <p>①版本号根据 小数点(.) 分割，转成int 数组，依次顺序比较数组里的 int数字，数字大则版本号大;</p>
                  <p>②若数组的int数字均相同，则比较两个数组的长度，长度长的版本号大长度也相等的则两个版本号相等;</p>
                </template>
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input
              v-if="addOrEditType === 'add'"
              v-model="form.version"
              maxlength="10"
              show-word-limit
              placeholder="版本号格式为xx.xx.xx，如1.0.0"></el-input>
            <span v-else>{{ form.version }}</span>
          </el-form-item>
          <el-form-item label="关键版本" prop="criticalVersionFlag">
            <template #label>
              <span>关键版本</span>&nbsp;
              <el-tooltip content="内容同原创建新固件中“关键版本为不可越过的版本，即当设定某个版本为关键版本后，即使发布了新的固件老固件也必须升级为关键版本，才可继续升级为最新版本" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-radio-group v-model="form.criticalVersionFlag">
              <!-- <el-radio :label="true">是</el-radio> -->
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="固件包" prop="package">
            <template #label>
              <span>固件包</span>&nbsp;
              <el-tooltip content="一般用于固件升级（OTA）的固件文件" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-upload
              class="upload-demo"
              action="/ota/v1/component/info/file/upload"
              :on-success="uploadSuccess"
              :headers="headerObj"
              :on-error="uploadError"
              :on-progress="uploadProgress"
              multiple
              :file-list="fileList">
              <el-button v-if="!uploadSuccessOrError" size="small" icon="el-icon-plus">上传固件</el-button>
              <div v-else>
                <el-input v-model="firmwarePackage.fileName" class="firmwareName" placeholder="已上传固件名字"></el-input>
              </div>
            </el-upload>
            <el-progress
              v-if="isUploading"
              :percentage="uploadPercentage"
            ></el-progress>
          </el-form-item>
          <el-form-item label="版本说明" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入适当说明信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="14" @click="handleClose">取消</el-button>
      <el-button type="primary" size="14" @click="handleSubmit">保存</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addFirmwareInfo, updateFirmwareVersion } from "@/api/product/firmware"
import store from '@/store'
export default {
  name: "addFirmwareDialog",
  props: {
    addOrEditType: {
      type: String,
      default: 'add' // add 新建 edit 编辑
    },
    queryFirmwareManageList: {
      type: Function,
      default: () => { }
    },
    queryVersionList: {
      type: Function,
      default: () => { }
    },
    pageType: {
      type: String,
      default: 'firmwareManage' // firmwareManage 固件管理 firmwareDetails 固件详情
    },
    rowsData: {
      type: Object,
      default: () => ({})
    },
    rowsInline: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validatePackage = (rule, value, callback) => {
      if (this.fileList.length === 0) {
        callback(new Error('请上传固件'))
      } else {
        callback()
      }
    }
    return {
      firmwareVersionVisible: false, // 弹窗是否显示
      form: {
        componentInfoId: '', // 固件Key
        name: '', // 固件名称
        version: '', // 固件版本
        criticalVersionFlag: false, // 关键版本
        description: '' // 版本说明
      },
      fileList: [], // 上传的固件文件
      uploadSuccessOrError: false, // 上传固件成功则展示固件基本信息否则不展示
      firmwarePackage: null, // 上传成功的固件包信息
      uploadLoading: '', // 上传固件弹窗的loading
      uploadPercentage: 0, // 上传进度百分比
      isUploading: false, // 是否正在上传
      headerObj: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      // 生成1到180的数字数组作为选项
      upgradeChannelOptions: Array.from({ length: 180 }, (_, index) => index + 1),
      rules: {
        package: { required: true, validator: validatePackage, trigger: 'blur' },
        name: [
          { required: true, message: '请输入固件名称', trigger: 'blur' }
          // { min: 1, max: 32, message: '请输入规范的固件名称', trigger: 'blur' }
          // { validator: this.validateName, trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入固件版本', trigger: 'blur' }
        ],
        criticalVersionFlag: [
          { required: true, message: '请选择关键版本', trigger: 'change' }
        ],
        isLaunch: [
          { required: true, message: '请选择是否上架', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    rowsData(newVal, oldVal) {
      this.form.componentInfoId = newVal.id
      if (this.pageType === 'firmwareManage') {
        this.form.name = newVal.name
      }
    },
    firmwareVersionVisible(val) {
      if (val) {
      // 每次打开弹窗时执行
        if (this.pageType === 'firmwareDetails' && this.addOrEditType === 'edit') {
          const newVal = this.rowsInline
          this.form.name = newVal.name
          this.form.version = newVal.version
          this.form.criticalVersionFlag = newVal.criticalVersionFlag
          this.form.description = newVal.description
          this.firmwarePackage = {
            fileName: newVal.fileName,
            size: newVal.size,
            sign: newVal.sign,
            url: newVal.url
          }
          this.fileList = [{
            name: newVal.fileName,
            size: newVal.size
          }]
          this.uploadSuccessOrError = true
        }
      } else {
      // 关闭时可清理表单
      this.$refs.form?.resetFields()
      this.fileList = []
      this.firmwarePackage = null
      this.uploadSuccessOrError = false
      }
    }
  },
  created() { },
  methods: {
    // 新建固件弹窗关闭
    handleClose() {
      this.firmwareVersionVisible = false
      this.$refs.form.resetFields()
      this.fileList = []
      this.uploadSuccessOrError = false
      this.firmwarePackage = {}
    },
    // 固件上传失败
    uploadError(err, file, fileList) {
      this.isUploading = false
      this.uploadPercentage = 0
      this.$message.error(err)
    },
    // 固件上传成功
    uploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        this.fileList = [file]
        this.uploadSuccessOrError = true
        this.firmwarePackage = response.data
        this.isUploading = false
        this.uploadPercentage = 0
      } else {
        this.$message.error(response.msg)
        this.isUploading = false
        this.uploadPercentage = 0
      }
    },
    // 固件包上传时的钩子
    uploadProgress(event, file, fileList) {
      this.isUploading = true
      this.uploadPercentage = Math.floor(event.percent)
    },
    // 提交
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.form,
            sign: this.firmwarePackage.sign,
            url: this.firmwarePackage.url,
            size: this.firmwarePackage.size,
            fileName: this.firmwarePackage.fileName,
            id: this.rowsInline.id
          }
          const func = this.addOrEditType === 'add' ? addFirmwareInfo : updateFirmwareVersion
          func(params).then((res) => {
            this.$message.success('上传成功')
            this.handleClose()
            this.uploadLoading = false
            // 返回固件管理列表页调用父组件方法刷新列表
            if (this.pageType === 'firmwareManage') {
              this.queryFirmwareManageList()
            } else if (this.pageType === 'firmwareDetails') {
              this.queryVersionList()
            }
          }).catch(err => {
            this.uploadLoading = false
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}

::v-deep .upload-demo {
  .el-upload-list {
    display: none;
  }

  .el-upload {
    width: 100%;

    .el-button {
      color: #275fe8;
      width: 100%;
      font-size: 14px;
    }
  }
}
</style>

